package com.ht.api.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.db.*;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户继承service
 * @author asq
 * @createTime 2025年4月4日 14:05:31
 */
@Slf4j
public class TransferService {
	/** 接口ID：获取待分配的离职成员列表 */
	private static final long API_ID = 1899986814131900416L;

    /**
     * 获取原成员可继承的用户列表
     * @param ds
     * @param param
     * @return
     */
    public static DbPage getHandoverUserInheritCustomers (DataSource ds, JSONObject param) {
        String transferId = param.getStr("transfer_id");
        Entity wxTransferUser = Db.createSqlParser("wx_transfer_user")
                .select("main_id,appid,type,handover_userid,takeover_userid,transfer_time,status").where("main_id", transferId).findOne(ds);

        String handoverUserid = wxTransferUser.getStr("handover_userid");
        String appid = wxTransferUser.getStr("appid");

        SqlParser sqlParser = param.toBean(SqlParser.class).setTable("wx_workuser_customer");
        sqlParser.where("type", 1);
        sqlParser.where("userid", handoverUserid);
        sqlParser.where("tenant_appid", appid);

        SqlParser subParser1 = SqlParser.create("wx_transfer_user_item").select("external_userid")
                .where("appid", appid)
                .where("handover_userid", handoverUserid).where("status", "in", Arrays.asList(0,1,2));

        sqlParser.where("external_userid", "not in", subParser1);

        SqlParser subParser2 = SqlParser.create("wx_transfer_user_item").select("external_userid")
                .where("appid", appid)
                .where("handover_userid", handoverUserid).where("status", "in", Arrays.asList(3,4,5))
                .where("DATEDIFF(NOW(), takeover_time)", "<", 180)
                .group("external_userid").having("count(1)", "<", 2);

        sqlParser.where("external_userid", "not in", subParser2);

        DbList list = sqlParser.query(ds);

		Integer pageNum = sqlParser.getPageNum();
		Integer pageSize = sqlParser.getPageSize();

		// 总记录数（有分页时，才查总记录数）
		Long total = null;
		if (pageNum != null) {
			// 注意调用sql.count方法后，将会失去limit字段，从而丢失页码信息
			total = sqlParser.count(ds);
		}

		// 翻译字典字段
		Mapper.translate(ds, list);

		// 构造分页对象
		DbPage dbPage = DbPage.builder()
				.pagenum(pageNum)
				.pagesize(pageSize)
				.total(total)
				.record(list)
				.build();

        return dbPage;
    }

    /**
     * 拉取刷新离职成员
     * @param ds
     * @param streamLoadConfig
     */
    public static void refreshUnassignedList(DataSource ds, StreamLoadConfig streamLoadConfig, long tenantId) {
    	// 查询开放平台（企业微信客户联系）下的所有应用，循环拉取
		DbList appList = Db.createSqlParser("open_app").select("main_id")
				.where("tenant_id", tenantId)
				.where("pid", "1868916871932284928").query();
		appList.stream().forEach(app -> {
			// 调用企微接口
			String appId = app.getStr("main_id");
			String str = OpenUtil.call(appId, API_ID, JSONUtil.createObj());
			
			// 如果企微接口调用成功，则操作本地数据库
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") == 0) {
				List<Entity> list = new ArrayList<>();
				JSONArray infoArr = obj.getJSONArray("info");

				
				// 对离职人员待分配的外部人员列表进行分组，统计每个离职人员的初始数量
			    Map<String, List<JSONObject>> infoGroup = infoArr.stream()
			    		.map(info -> (JSONObject)info).collect(Collectors.groupingBy(info -> {
							return info.getStr("handover_userid") + "," + info.getStr("dimission_time");
						}));
			    infoGroup.entrySet().forEach(info -> {
			    	String groupKey = info.getKey();
			    	String[] keyArr = groupKey.split(","); 
			    	String handoverUserid = keyArr[0];
			    	String dimissionTime = keyArr[1];
			    	int initCnt = info.getValue().size();
			    	
			    	// 查询该离职人员是否已有数据，没有数据的才写入表
					boolean exists = Db.createSqlParser("wx_workuser_dimission")
							.where("appid", appId)
							.where("handover_userid", handoverUserid)
							.hasRow(ds);

					if (!exists) {
						Entity wxWorkuserDimission = Entity.create("wx_workuser_dimission");
						wxWorkuserDimission.set("appid", appId);
						wxWorkuserDimission.set("handover_userid", handoverUserid);
						wxWorkuserDimission.set("dimission_time", HtUtil.formatTimeString(dimissionTime));
						wxWorkuserDimission.set("status", 0);
						wxWorkuserDimission.set("init_cnt", initCnt);
						wxWorkuserDimission.set("wait_cnt", initCnt);
						list.add(wxWorkuserDimission);

						for (int i = 0; i < info.getValue().size(); i++) {
							JSONObject item = infoArr.getJSONObject(i);
							String externalUserid = item.getStr("external_userid");

							Entity wxWorkuserDimissionExternal = Entity.create("wx_workuser_dimission_external");
							wxWorkuserDimissionExternal.set("appid", appId);
							wxWorkuserDimissionExternal.set("handover_userid", handoverUserid);
							wxWorkuserDimissionExternal.set("external_userid", externalUserid);
							wxWorkuserDimissionExternal.set("status", 0);
							list.add(wxWorkuserDimissionExternal);
						}

					}

					// 将离职的客服标记为5：退出企业
					Entity wxWorkUser = Db.createSqlParser("wx_workuser").where("tenant_appid", appId)
							.where("userid", handoverUserid).findOne(ds);
					if (wxWorkUser != null) {
						Entity wxWorkUserUpdate = Entity.create("wx_workuser");
						wxWorkUserUpdate.set("tenant_appid", appId);
						wxWorkUserUpdate.set("userid", handoverUserid);
						wxWorkUserUpdate.set("status", 5);
						list.add(wxWorkUserUpdate);
					}

			    });
				
				Db.insertBatchWithStream(streamLoadConfig, list);
			} else {
				log.error("[GetDimissionListFunctionCall]拉取刷新离职成员时企微接口返回错误：{}", obj.getStr("errmsg"));
			}
		});
    }

}
